<?php
namespace app\controller;

use app\BaseController;
use app\model\Blogs;
use think\facade\Request;
use think\facade\View;

class Index
{
    public function index(Request $request)
    {
        // 查询参数
        $keyword = $request::param('keyword');
        $category_id = $request::param('category_id');


        // 所有博客的数据集 预载入关联的用户表与分类表
        $blogs = Blogs::with(['users', 'categories'])
            ->when($keyword, function ($query) use ($keyword){
                $query->where(function ($query) use ($keyword){
                    $query->where('title', 'like', "%{$keyword}%")
                        ->whereOr('content', 'like', "%{$keyword}%");
            });

        })
            ->when($category_id, function ($query) use ($category_id){
                $query->where('category_id', $category_id);
            })
            ->where('status', 1)
            ->order('updated_at', 'desc')
            ->paginate(['list_rows' => 5, 'query' => Request::param(['keyword', 'category_id'])]);

        // 博客的数量
        $count = $blogs->total();
        // 获取分页显示
        $page = $blogs->render();

        return View::fetch('index/index', [
            'blogs' => $blogs,
            'count' => $count,
            'page' => $page,
        ]);
    }

    // 获取token
    public function getToken()
    {
    $request = \think\facade\Request::instance();

    echo $request->buildToken();
    }
}
